

library(scales)

# Function factory for secondary axis transforms
train_sec <- function(primary, secondary) {
  from <- range(secondary)
  to   <- range(primary)
  # Forward transform for the data
  forward <- function(x) {
    rescale(x, from = from, to = to)
  }
  # Reverse transform for the secondary axis
  reverse <- function(x) {
    rescale(x, from = to, to = from)
  }
  list(fwd = forward, rev = reverse)
}

sec <- with(data_5, train_sec(v2stcritrecadm, conflicts))

violence_plot <-
  ggplot(data_5, aes(x = year)) +
  geom_line(aes(y = v2stcritrecadm), colour = "darkgrey") +
  geom_point(aes(y = v2stcritrecadm), colour = "black", size = 0.8) +
  geom_point(aes(y = sec$fwd(conflicts)), colour = "black", size = 0.8) +
  geom_line(aes(y = sec$fwd(conflicts)), colour = "#DD3497") +
  scale_y_continuous(sec.axis = sec_axis(~sec$rev(.), name = "Communal Violence Over Recruitment")) +
  theme_bw() +
  theme(axis.line.y.right = element_line(color = "#DD3497"), 
        axis.ticks.y.right = element_line(color = "#DD3497"),
        axis.text.y.right = element_text(color = "#DD3497"), 
        axis.title.y.right = element_text(color = "#DD3497", angle = 90),
        panel.grid.minor = element_blank(), 
        panel.grid.major.x = element_blank(),
        axis.title.x = element_blank(),
        #axis.line.y.left = element_blank(),
        axis.line = element_line(colour = "black"),
        panel.border = element_blank(),
        panel.background = element_rect(fill = "transparent",colour = NA),
        plot.background = element_rect(fill = "transparent",colour = NA)) +
  scale_x_continuous(breaks=seq(1998, 2014, 2)) +
  ylab("Meritocracy Index")

ggsave(filename = "./_4_outputs/figures/figure_a7.png", plot = violence_plot, width = 6, height = 4)
